package edu.hznu.retroSnakerPlanServer.entity;

import edu.hznu.retroSnakerPlanServer.service.ByteSerializable;
import edu.hznu.retroSnakerPlanServer.utils.ByteUtils;


/**
 * create by Cliven on 2018-05-31 16:01
 * 蛇的身体节点
 *
 * @author Cliven
 */
public class SnakeNode implements ByteSerializable {
    private Integer x;
    private Integer y;
    private Integer colorType;
    private Integer id;
    private Integer direction;

    public static final int SIZE = 7;


    /**
     * 解析数组构造实体
     *
     * @param array  字节数组
     * @param offset 偏移量
     * @return 实例
     * @author Cliven
     * @since 2018-05-31 20:54:29
     */
    public static SnakeNode getInstance(Byte[] array, int offset) {
        if ((offset + SIZE) > array.length) {
            throw new IllegalArgumentException("Out of source array range...");
        }
        SnakeNode snakeNode = new SnakeNode();
        snakeNode.setX(ByteUtils.byteToShortInteger(array, offset));
        offset += 2;
        snakeNode.setY(ByteUtils.byteToShortInteger(array, offset));
        offset += 2;
        return snakeNode.setColorType((int) array[offset++])
                .setId(array[offset++] & 0xFF)
                .setDirection(array[offset] & 0xFF);
    }

    public SnakeNode() {
    }

    public Integer getX() {
        return x;
    }

    public SnakeNode setX(Integer x) {
        this.x = x;
        return this;
    }

    public Integer getY() {
        return y;
    }

    public SnakeNode setY(Integer y) {
        this.y = y;
        return this;
    }

    public Integer getColorType() {
        return colorType;
    }

    public SnakeNode setColorType(Integer colorType) {
        this.colorType = colorType;
        return this;
    }

    public Integer getId() {
        return id;
    }

    public SnakeNode setId(Integer id) {
        this.id = id;
        return this;
    }

    public Integer getDirection() {
        return direction;
    }

    public SnakeNode setDirection(Integer direction) {
        this.direction = direction;
        return this;
    }

    /**
     * 序列化某个对象为byte数组
     *
     * @return 字节数组
     * @author Cliven
     * @since 2018-06-01 08:06:53
     */
    @Override
    public Byte[] serial() {
        Byte[] res = new Byte[SIZE];
        int offset = 0;

        res[offset++] = (byte) (this.x & 0xFF);
        res[offset++] = (byte) ((this.x >> 8) & 0xFF);

        res[offset++] = (byte) (this.y & 0xFF);
        res[offset++] = (byte) ((this.y >> 8) & 0xFF);

        res[offset++] = (byte) (this.colorType & 0xFF);
        res[offset++] = (byte) (this.id & 0xFF);
        res[offset] = (byte) (this.direction & 0xFF);

        return res;
    }

    @Override
    public String toString() {
        return "SnakeNode{" +
                "x=" + x +
                ", y=" + y +
                ", colorType=" + colorType +
                ", id=" + id +
                ", direction=" + direction +
                '}';
    }
}
